package org.korecky.gnotedigitalorganizer.settings;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 
 * @author Ing. Vladislav Korecký <vladislav_korecky@gordic.cz>
 */
public class ApplicationSettingsHelper {
    /**
     * @throws Exception
     * 
     */
    public static ApplicationSettings loadApplicationSettings(String settingsFilePath) throws Exception {
	ApplicationSettings appSettings = null;
	try {
	    File appSettingsFile = new File(settingsFilePath);
	    if (appSettingsFile.exists()) {
		// Create file input stream.
		FileInputStream fstream = new FileInputStream(appSettingsFile);
		XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(fstream));
		appSettings = (ApplicationSettings) decoder.readObject();
		decoder.close();
	    }
	}
	catch (Exception exc) {
	    throw new Exception("Cannot load \"Application Settings\"", exc);
	}

	return appSettings;
    }

    /**
     * @throws Exception
     * @throws FileNotFoundException
     * 
     */
    public static void saveApplicationSettings(String settingsFilePath, ApplicationSettings appSettings) throws Exception {
	try {
	    File appSettingsFile = new File(settingsFilePath);
	    if (!appSettingsFile.exists()) {
		File appSettingsFolder = appSettingsFile.getParentFile();
		if (!appSettingsFolder.exists()) {
		    appSettingsFolder.mkdirs();
		}
	    }

	    // Create output stream.
	    FileOutputStream fos = new FileOutputStream(appSettingsFile);
	    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(fos));
	    encoder.writeObject(appSettings);
	    encoder.close();
	}
	catch (Exception exc) {
	    throw new Exception("Cannot save \"Application Settings\"", exc);
	}
    }
}
